package org.easymodelers.template.utils;

import java.lang.reflect.Method;
import java.util.Map;

import org.easymodelers.template.TemplateProcessingException;
import org.eclipse.emf.ecore.EObject;

public abstract class ContextManager {
	private static String firstUpper(String s) {
		return s.substring(0, 1).toUpperCase() + s.substring(1);
	}

	private static Object getValue(Object o, String attributeName) {
		Class clazz = o.getClass();
		String getMethodName = "get" + firstUpper(attributeName);
		Method getMethod = null;

		try {
			getMethod = clazz.getMethod(getMethodName);

			if (getMethod==null) {
				String message = "Unable to find method "+getMethod+" for class "+clazz.getName();
				throw new TemplateProcessingException(message);
			}

			return getMethod.invoke(o);
		} catch(Exception ex) {
			ex.printStackTrace();
			Class returnType = getMethod.getReturnType();
			String message = "Error during the execution of method "+getMethodName+" for class "+clazz.getName()
					+ " - return: "+returnType.getName();
			throw new TemplateProcessingException(message, ex);
		}
	}
	
	public static Object getValueFromContext(Map<String,Object> context, String contextValue) {
		int index = contextValue.indexOf(".");
		Object value = null;
		if (index!=-1) {
			Object tmpO = null;
			String remainingFieldName = contextValue;
			while (index!=-1) {
				String o1Name = remainingFieldName.substring(0, index);
				String o1Attribute = remainingFieldName.substring(index+1);
				remainingFieldName = o1Attribute;
				if (tmpO==null) {
					tmpO = context.get(o1Name);
					if (tmpO==null) {
						String message = "The key "+o1Name+" isn't present in the context.";
						throw new TemplateProcessingException(message);
					}
				}
				index = remainingFieldName.indexOf(".");
				if (index==-1) {
					value = getValue(tmpO, o1Attribute);
				} else {
					o1Attribute = remainingFieldName.substring(0, index);
					try {
						tmpO = getValue(tmpO, o1Attribute);
					} catch(Exception ex) {
						String message = "The field "+o1Attribute+" isn't present in the object "
											+o1Name+" in the context.";
						throw new TemplateProcessingException(message, ex);
					}
				}
			}
		} else {
			value = context.get(contextValue);
		}

		return value;
	}
}
